﻿namespace com.stifel.SharePoint
{
    using System;

    using com.stifel.Exceptions.SharePointExceptions;
    using com.stifel.Extensions.SharePointExtensions;

    using Microsoft.SharePoint;

    public abstract class BaseDao
    {
        #region Fields

        string _CurrentWebUrl;
        string _ListTitle;

        #endregion Fields

        #region Constructors

        public BaseDao( string listName )
        {
            this.listName = listName;
        }

        #endregion Constructors

        #region Properties

        public string CurrentWebUrl
        {
            get
            {
                return _CurrentWebUrl;
            }
            set
            {
                if ( !value.Equals( _CurrentWebUrl ) )
                {
                    _CurrentWebUrl = value;
                    validateListExistence( );
                }
            }
        }

        public string ListTitle
        {
            get
            {
                if ( string.IsNullOrEmpty( _ListTitle ) )
                {
                    using ( SPSite spSite = new SPSite( CurrentWebUrl ) )
                    {
                        using ( SPWeb spWeb = spSite.OpenWeb( ) )
                        {
                            _ListTitle = spWeb.Lists.GetListTitle( listName );
                        }
                    }
                }
                return _ListTitle;
            }
        }

        string listName
        {
            get;
            set;
        }

        #endregion Properties

        #region Methods

        public bool ListExists( )
        {
            return string.IsNullOrEmpty( ListTitle ) ? false : true;
        }

        void validateListExistence( )
        {
            if ( !ListExists( ) )
                throw new ListNotFoundException( listName, CurrentWebUrl );
        }

        #endregion Methods
    }
}